import { WebSocketServer ,WebSocket, EventEmitter} from "ws";
import { Connection } from "./Connection";
import { ApiMsgEnum, IModel } from "../Common";
/**
 * 维护所有客户端的连接，并且提供方法给外界调用
 */
export class MyServer extends EventEmitter{
    port:number
    wss:WebSocketServer
    // 创建一个Map对象，用于存储API处理函数
    apiMap:Map<ApiMsgEnum,Function>=new Map()
    connections:Set<Connection>=new Set()

    constructor({port}:{port:number}){
        super()
        this.port=port
    }

    start(){
        return new Promise((resolve,reject)=>{
            // 创建 WebSocket 服务器，监听 9876 端口
            this.wss= new WebSocketServer({
                port:9876,
            })
            this.wss.on("listening",()=>{
                resolve(true)
            })
            this.wss.on("close",()=>{
                reject(false)
            })
            this.wss.on("error",(e)=>{
                reject(e)
            })
            //connection 事件：当有新的客户端连接时触发
            this.wss.on("connection",(ws:WebSocket)=>{
                const connection = new Connection(this,ws)
                this.connections.add(connection)
                this.emit("connection",connection)
                
                connection.on("close",()=>{
                    this.connections.delete(connection)
                    this.emit("disconnection",connection)
                    
                })
            })
        })
        
    }
    //设置api 用websocket模拟一个api服务
    /**
     * 在apiMap里保存一对键为ApiMsgEnum，值为Function的键值对.
     *  */ 
    setApi <T extends keyof IModel['api']>(name:T,cb:(connection:Connection,args:IModel['api'][T]['req'])=>void){
        //把cb保存到apiMap中
        this.apiMap.set(name,cb)
    }
}